package com.ken.common.event.plugins.msghandler.chain.impl;

import com.ken.common.event.apply.handle.EventHandler;
import com.ken.common.event.framework.processor.EventMsgPostProcessor;
import com.ken.common.event.plugins.msghandler.chain.AbstractMsgChain;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * 前后置处理器的责任链
 */
@Component
@Order(30)
@Slf4j
public class BeginProcessorChain extends AbstractMsgChain<EventHandler> {

    @Autowired(required = false)
    private List<EventMsgPostProcessor> postProcessors;

    @Override
    public void coreRun(ChainContext context, EventHandler eventHandler) {
        log.debug("[Msg-Handle] - 消息前置处理器开始执行...");
        if (!CollectionUtils.isEmpty(postProcessors)) {
            for (EventMsgPostProcessor postProcessor : postProcessors) {
                if (postProcessor.isSupport(context.getEventTypeStr(), context.getEventMessage(), eventHandler)) {
                    if (!postProcessor.beginProcessor(context.getEventMessage(), eventHandler)) {
                        log.debug("[Msg-Handle] - 前置处理器中断了消息的后续消费！");
                        return;
                    }
                }
            }
        }
        log.debug("[Msg-Handle] - 消息后置处理器执行完成！");

        //继续往后透传
        super.nextInvoce(context, eventHandler);
    }
}
